
package com.gitee.jmash.rbac.service;

import java.util.List;
import java.util.UUID;
import com.gitee.jmash.core.orm.DtoPage;
import com.gitee.jmash.core.orm.DtoTotal;
import com.gitee.jmash.core.orm.cdi.JpaTenantService;
import com.gitee.jmash.core.orm.jpa.TenantEntityManager;
import com.gitee.jmash.core.orm.tenant.TenantService;
import com.gitee.jmash.core.transaction.JakartaTransaction;
import com.gitee.jmash.rbac.dao.OperationDao;
import com.gitee.jmash.rbac.dao.PermDao;
import com.gitee.jmash.rbac.entity.OperationEntity;
import jakarta.enterprise.inject.Typed;
import jakarta.enterprise.inject.spi.CDI;
import jakarta.persistence.EntityManager;
import jakarta.persistence.PersistenceContext;
import jakarta.transaction.Transactional;
import jakarta.transaction.Transactional.TxType;
import jakarta.validation.executable.ValidateOnExecution;
import jmash.rbac.protobuf.OperationReq;

/**
 * 操作表 rbac_operation读服务.
 *
 * @author <a href="mailto:service@crenjoy.com">crenjoy</a>
 */
@Typed(OperationRead.class)
@Transactional(TxType.SUPPORTS)
@JpaTenantService
@ValidateOnExecution
public class OperationReadBean implements OperationRead, JakartaTransaction {

  protected TenantEntityManager tem = new TenantEntityManager();
  
  protected OperationDao operationDao = new OperationDao(this.tem);
  protected PermDao permDao = new PermDao(this.tem);

  @PersistenceContext(unitName = "ReadRbac")
  public void setEntityManager(EntityManager entityManager) {
    this.tem.setEntityManager(entityManager,false);
  }
	
  @Override
  @SuppressWarnings("unchecked")
  public <T extends TenantService> T setTenant(String tenant) {
    this.tem.setTenant(tenant);
    return (T) this;
  }
  
  @Override
  public EntityManager getEntityManager() {
    return this.tem.getEntityManager();
  }
  
  @Override
  public void setTenantOnly(String tenant) {
    this.tem.setTenantOnly(tenant);
  }
  
  @Override
  public String getTenant() {
    return  this.tem.getTenant();
  }

  @Override
  public OperationEntity findById(UUID entityId) {
    return operationDao.find(entityId);
  }

  @Override
  public DtoPage<OperationEntity,DtoTotal> findPageByReq(OperationReq req) {
    return operationDao.findPageByReq(req);
  }

  @Override
  public List<OperationEntity> findListByReq(OperationReq req) {
    return operationDao.findListByReq(req);
  }

  @Override
  public boolean checkOperationCodeUnique(String operationCode) {
    List<OperationEntity> operationList = operationDao.findListByReq(OperationReq.newBuilder().setOperationCode(operationCode).build());
    if(operationList.size() > 0) {
      return true;
    }
    return false;
  }
  
  @Override
  public void close() throws Exception {
    CDI.current().destroy(this);
  }
}
